package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.PlanDevelopment;
import net.hn.hnms.biz.plan.mapper.PlanDevelopmentMapper;
import net.hn.hnms.biz.plan.request.PlanDevelopmentReq;
import net.hn.hnms.biz.plan.service.IPlanDevelopmentService;
import net.hn.hnms.biz.plan.vo.PlanDevelopmentVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhaoyang
 * 开拓计划管理服务层实现
 * @date 2022-08-01
 */

@Service
@DS("master")
public class PlanDevelopmentServiceImpl extends BaseService<PlanDevelopment, PlanDevelopmentVO> implements IPlanDevelopmentService {

    private PlanDevelopmentMapper planDevelopmentMapper;

    public PlanDevelopmentServiceImpl(PlanDevelopmentMapper planDevelopmentMapper) {
        this.planDevelopmentMapper = planDevelopmentMapper;
    }

    /**
     * @param planDevelopment
     * @param pageQuery       查询开拓计划列表
     */
    @Override
    public ResponsePage<PlanDevelopmentVO> selectPageList(PlanDevelopmentReq planDevelopment, PageQuery pageQuery) {

        Page<PlanDevelopment> page = planDevelopmentMapper.selectPage(pageQuery.build(), buildQuery(planDevelopment).orderByDesc(PlanDevelopment::getDevelopmentPlanCode).orderByDesc(PlanDevelopment::getCreateTime));

        List<PlanDevelopmentVO> list = page.getRecords().stream().map(o -> convert(o, PlanDevelopmentVO.class, o.getDevelopmentPlanType())).collect(Collectors.toList());
        return new ResponsePage<>(list, page.getTotal());
    }

    /**
     * 构造查询条件
     *
     * @param req
     * @return LambdaQueryWrapper<PlanDevelopment> 查询条件
     */
    private LambdaQueryWrapper<PlanDevelopment> buildQuery(PlanDevelopmentReq req) {
        LambdaQueryWrapper<PlanDevelopment> lqw = new LambdaQueryWrapper<PlanDevelopment>()
                .like(StrUtil.isNotBlank(req.getDevelopmentPlanCode()), PlanDevelopment::getDevelopmentPlanCode, req.getDevelopmentPlanCode())
                .like(StrUtil.isNotBlank(req.getDevelopmentPlanName()), PlanDevelopment::getDevelopmentPlanName, req.getDevelopmentPlanName())
                .eq(StrUtil.isNotBlank(req.getDevelopmentPlanType()), PlanDevelopment::getDevelopmentPlanType, req.getDevelopmentPlanType())
                .eq(StrUtil.isNotBlank(req.getStatus()), PlanDevelopment::getStatus, req.getStatus());
        return lqw;
    }

    /**
     * @param planDevelopment 查询开拓计划列表
     */
    @Override
    public List<PlanDevelopmentVO> selectList(PlanDevelopmentReq planDevelopment) {
        List<PlanDevelopment> list = planDevelopmentMapper.selectList(buildQuery(planDevelopment));
        return list.stream().map(o -> convert(o, PlanDevelopmentVO.class, o.getDevelopmentPlanType())).collect(Collectors.toList());
    }

    /**
     * @param planDevelopment 新增开拓计划
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(PlanDevelopmentReq planDevelopment) {

        PlanDevelopment insertObj = new PlanDevelopment();
        copyProperties(planDevelopment, insertObj, planDevelopment.getDevelopmentPlanType());
        //自动生成 计划名称 计划编号
        insertObj.setDevelopmentPlanName(generatePlanName(planDevelopment.getDevelopmentPlanType(),insertObj.getPlanStartDate()));
        insertObj.setDevelopmentPlanCode(generatePlanCode(planDevelopment.getDevelopmentPlanType(),insertObj.getPlanStartDate()));
        insertObj.setStatus("0");
        QueryWrapper<PlanDevelopment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("development_plan_code", insertObj.getDevelopmentPlanCode());
        if (planDevelopmentMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        return planDevelopmentMapper.insert(insertObj);
    }

    /**
     * @param idList 批量删除 id集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        planDevelopmentMapper.deleteBatchIds(idList);
    }

    /**
     * @param planDevelopment 单个修改 按照主键修改信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(PlanDevelopmentReq planDevelopment) {
        if (StrUtil.isBlank(planDevelopment.getDevelopmentPlanId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        PlanDevelopment updateObj = new PlanDevelopment();
        copyProperties(planDevelopment, updateObj, planDevelopment.getDevelopmentPlanType());
        updateObj.setDevelopmentPlanName(generatePlanName(planDevelopment.getDevelopmentPlanType(),updateObj.getPlanStartDate()));
        updateObj.setDevelopmentPlanCode(generatePlanCode(planDevelopment.getDevelopmentPlanType(),updateObj.getPlanStartDate()));
        QueryWrapper<PlanDevelopment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("development_plan_code", updateObj.getDevelopmentPlanCode());
        queryWrapper.ne("development_plan_id", updateObj.getDevelopmentPlanId());
        if (planDevelopmentMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        int updateCount = planDevelopmentMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
    }

    /**
     * @param id 按主键id查询详情
     */
    @Override
    public PlanDevelopmentVO selectDetailById(String id) {
        PlanDevelopment planDevelopment = planDevelopmentMapper.selectById(id);
        if (planDevelopment == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(planDevelopment, PlanDevelopmentVO.class);
    }


    /**
     * 启用/禁用
     *
     * @param id     数据id
     * @param status status: 0:启用 1:禁用
     */
    public void changeStatus(String id, Integer status) {
        if (status == 1 || status == 0) {
            PlanDevelopment planMining = planDevelopmentMapper.selectById(id);
            if (planMining == null) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            planMining.setStatus(status + "");
            int res = planDevelopmentMapper.updateById(planMining);
            if (res == 0) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            return;
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }
}
